#!/usr/bin/perl -s

my $Help = ($h or $help or $H or $HELP);

&print_help if $Help;

my $Keep = ($k or $keep or $K or $KEEP);
my $Gzip = ($g or $gzip or $z);

use strict;

my $dir = ($ARGV[0] or 'ionosphere');
chdir $dir or die "Could not cd into $dir/\n";
my @files = glob('*_b1.*');

my $file1;   # _b1 file
my $file2;   # _b2 file
my $fileout; # concatenated file
my $err;     # error message from cat

foreach $file1 (sort @files){
    $file2 = $file1;
    $file2 =~ s/b1/b2/;
    $fileout = $file1;
    $fileout =~ s/_b1//;
    print "cat $file1 $file2 > $fileout\n";
    $err = `cat $file1 $file2 > $fileout`;
    die "Error occured: $err\n" if $err;
    unlink($file1, $file2) unless $Keep;
}

if($Gzip){
    @files = glob('*.idl');
    foreach $fileout (sort @files){
	$err = `gzip -f $fileout`;
	die "Error occured: $err\n" if $err;
    }
}

exit 0;

##############################################################################

sub print_help{

    print "
Purpose:
   Concatanate north and south blocks into a single idl file.

Usage:
   pION [-h] [-k] [-g] [DIR]

   -h -help    - print this help message
   -k -keep    - keep original files
                 Default is to delete the two hemisphere files.
   -g -gzip    - gzip the output files
                 Default is to leave the output files uncompressed
   DIR         - name of the directory to process
                 Default is DIR = 'ionosphere'

Examples:

   Process files in the ionosphere/ directory:
pION

   Process files in the iono_new/ directory and keep originals:
pION -k iono_new
  
";
    exit 1;

}
